// pages/address/address.js
const {
  getCustomerAddress,
  deleteAddress,
  setDefaultAddress,
} = require("../../api/address.js");
const userStore = require("../../store/userStore.js");

Page({
  data: {
    loading: true,
    addressList: [],
    isLoggedIn: false,
    isSelectMode: false, // 是否是地址选择模式
  },

  onLoad(options) {
    // 检查是否是地址选择模式
    const isSelectMode = options.select === "true";
    this.setData({
      isSelectMode: isSelectMode,
    });

    // 如果是选择模式，设置页面标题
    if (isSelectMode) {
      wx.setNavigationBarTitle({
        title: "选择收货地址",
      });
    }

    // 检查登录状态
    this.checkLoginStatus();
  },

  onShow() {
    if (this.data.isLoggedIn) {
      this.loadAddressList();
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const userInfo = userStore.getUserInfo();
    const isLoggedIn = !!userInfo;

    this.setData({
      isLoggedIn,
      loading: false,
    });

    if (!isLoggedIn) {
      this.showAuthModal();
    }
  },

  /**
   * 显示授权弹窗
   */
  showAuthModal() {
    wx.showModal({
      title: "需要授权",
      content: "请先授权登录后再使用此功能",
      showCancel: true,
      cancelText: "取消",
      confirmText: "去授权",
      success: (res) => {
        if (res.confirm) {
          this.goToAuth();
        } else {
          wx.navigateBack();
        }
      },
    });
  },

  /**
   * 跳转到授权页面
   */
  goToAuth() {
    // 保存当前页面路径，授权后返回
    getApp().globalData.returnToPage = "/pages/address/address";

    wx.navigateTo({
      url: "/pages/index/index",
    });
  },

  /**
   * 加载地址列表
   */
  async loadAddressList() {
    try {
      this.setData({ loading: true });

      const response = await getCustomerAddress();

      if (response.code === 0) {
        // 显示所有地址（包括失效地址）
        const allAddresses = response.data || [];

        this.setData({
          addressList: allAddresses,
        });
      } else {
        wx.showToast({
          title: response.message || "加载失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("加载地址列表失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 添加新地址
   */
  addAddress() {
    if (!this.data.isLoggedIn) {
      this.showAuthModal();
      return;
    }

    wx.navigateTo({
      url: "/pages/address-edit/address-edit",
    });
  },

  /**
   * 编辑地址
   */
  editAddress(e) {
    if (!this.data.isLoggedIn) {
      this.showAuthModal();
      return;
    }

    const { address } = e.currentTarget.dataset;

    // 如果是选择模式，只有有效地址可以编辑
    if (this.data.isSelectMode && address.status !== 1) {
      wx.showToast({
        title: "失效地址不可编辑",
        icon: "none",
      });
      return;
    }

    // 将地址数据存储到全局数据中，供编辑页面使用
    getApp().globalData.editAddressData = address;

    wx.navigateTo({
      url: `/pages/address-edit/address-edit?id=${address.id}`,
    });
  },

  /**
   * 选择地址（点击地址信息区域）
   */
  selectAddress(e) {
    if (!this.data.isLoggedIn) {
      this.showAuthModal();
      return;
    }

    const { address } = e.currentTarget.dataset;

    // 如果是选择模式，只允许选择有效地址
    if (this.data.isSelectMode) {
      if (address.status !== 1) {
        wx.showToast({
          title: "失效地址不可选择",
          icon: "none",
        });
        return;
      }
      this.selectAddressForOrder(address);
      return;
    }

    // 非选择模式下，点击地址信息区域跳转到编辑页面
    getApp().globalData.editAddressData = address;
    wx.navigateTo({
      url: `/pages/address-edit/address-edit?id=${address.id}`,
    });
  },

  /**
   * 选择地址用于订单
   */
  selectAddressForOrder(address) {
    // 将选中的地址存储到全局数据中
    getApp().globalData.selectedAddress = address;

    // 返回上一页
    wx.navigateBack();
  },

  /**
   * 删除地址
   */
  deleteAddress(e) {
    if (!this.data.isLoggedIn) {
      this.showAuthModal();
      return;
    }

    const { address } = e.currentTarget.dataset;

    wx.showModal({
      title: "确认删除",
      content: `确定要删除地址"${address.fullAddress}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.confirmDeleteAddress(address.id);
        }
      },
    });
  },

  /**
   * 确认删除地址
   */
  async confirmDeleteAddress(addressId) {
    try {
      // 先添加删除动画
      const addressList = this.data.addressList.map((item) => {
        if (item.id === addressId) {
          return { ...item, deleting: true };
        }
        return item;
      });
      this.setData({
        addressList: addressList,
      });

      // 等待动画完成
      await new Promise((resolve) => setTimeout(resolve, 300));

      wx.showLoading({ title: "删除中..." });

      const response = await deleteAddress({ id: addressId });

      if (response.code === 0) {
        wx.hideLoading();
        wx.showToast({
          title: "删除成功",
          icon: "success",
        });

        // 本地删除地址，避免重新加载导致的闪屏
        const updatedAddressList = this.data.addressList.filter(
          (item) => item.id !== addressId
        );
        this.setData({
          addressList: updatedAddressList,
        });
      } else {
        wx.hideLoading();
        wx.showToast({
          title: response.message || "删除失败",
          icon: "none",
        });

        // 删除失败，恢复状态
        const addressList = this.data.addressList.map((item) => {
          if (item.id === addressId) {
            return { ...item, deleting: false };
          }
          return item;
        });
        this.setData({
          addressList: addressList,
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error("删除地址失败:", error);
      wx.showToast({
        title: "删除失败，请重试",
        icon: "none",
      });

      // 删除失败，恢复状态
      const addressList = this.data.addressList.map((item) => {
        if (item.id === addressId) {
          return { ...item, deleting: false };
        }
        return item;
      });
      this.setData({
        addressList: addressList,
      });
    }
  },

  /**
   * 设置默认地址
   */
  setDefaultAddress(e) {
    if (!this.data.isLoggedIn) {
      this.showAuthModal();
      return;
    }

    const { address } = e.currentTarget.dataset;

    if (address.isDefault) {
      return; // 已经是默认地址
    }

    wx.showModal({
      title: "设置默认地址",
      content: `确定要将"${address.fullAddress}"设为默认地址吗？`,
      success: (res) => {
        if (res.confirm) {
          this.confirmSetDefault(address.id);
        }
      },
    });
  },

  /**
   * 确认设置默认地址
   */
  async confirmSetDefault(addressId) {
    try {
      wx.showLoading({ title: "设置中..." });

      const response = await setDefaultAddress({ id: addressId });

      if (response.code === 0) {
        wx.hideLoading();
        wx.showToast({
          title: "设置成功",
          icon: "success",
        });

        // 重新加载地址列表
        this.loadAddressList();
      } else {
        wx.hideLoading();
        wx.showToast({
          title: response.message || "设置失败",
          icon: "none",
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error("设置默认地址失败:", error);
      wx.showToast({
        title: "设置失败，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    if (this.data.isLoggedIn) {
      this.loadAddressList().finally(() => {
        wx.stopPullDownRefresh();
      });
    } else {
      wx.stopPullDownRefresh();
    }
  },
});
